package cn.lwalan.commonUtils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther: Alan liu
 * @Date: 2018/9/26 11:43
 * @Description: 测试并发案例
 */
public class TestConcurrentRequest {

    /**
     * 总的请求数
     */
    public static final int requestTotal = 1000;
    /**
     * 同一时刻最大的并发数
     */
    public static final int concurrentThreadNum = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(requestTotal);
        Semaphore semaphore = new Semaphore(concurrentThreadNum);
        for (int i = 0; i< requestTotal; i++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    String result = testRequestUri();
                    System.out.println(Thread.currentThread().getName() + " result: "+result);
                    semaphore.release();
                } catch (InterruptedException e) {
                    System.out.println("exception " + e.getMessage());
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("请求完成");
    }

    private static String testRequestUri() {
//        return HttpClientUtil.get("https://localhost:8080/test");
        return "hello";
    }
}
